import os
import inspect
from threading import Thread
import time
import platform

sys_os = platform.system()
PATH = os.getcwd()
_log_rewriting_time = "00:00"
_while_wait_time = 1
# _time=None


class logging:
    debug: str = "DEBUG"
    info: str = "INFO"
    warning: str = "WARNING"
    error: str = "ERROR"
    critical: str = "CRITICAL"

# 日志类


class getLogger(Thread):
    def __init__(self, logger_name):
        self.stop = False
        Thread.__init__(self)
        now_dirs = os.getcwd()
        if sys_os == 'Windows':
            now_dirs = PATH + '\\logs\\'
            if os.path.exists(now_dirs) is False:
                try:
                    os.mkdir(now_dirs)
                except FileNotFoundError or FileExistsError:
                    print("Critical Error: Can't create folder for save logs")
        if sys_os == 'Linux':
            now_dirs = PATH + '/logs/'
            if os.path.exists(now_dirs) is False:
                try:
                    os.mkdir(now_dirs)
                except FileNotFoundError or FileExistsError:
                    print("Critical Error: Can't create folder for save logs")
        self.logger_name = logger_name
        self.Create_logger()
        self.start()

    def remove_old_log(self):
        old_log_time = time.strftime(
            "%Y-%m-%d", time.localtime(time.time() - 7 * 24 * 3600))
        try:
            if os.path.isdir(PATH + "/logs/" + old_log_time):
                for name in os.listdir(PATH + "/logs/" + old_log_time):
                    os.remove(PATH + "/logs/" + old_log_time + "/" + name)
                os.removedirs(PATH + "/logs/" + old_log_time)
            else:
                pass
        except Exception as e:
            pass

    def return_localtime(self):
        _time = time.strftime("%Y-%m-%d", time.localtime())
        return _time

    def Create_logger(self):
        _localtime = self.return_localtime()
        self.log_data_dir = PATH + "/logs/" + _localtime
        try:
            if os.path.isdir(self.log_data_dir):
                pass
            else:
                os.mkdir(self.log_data_dir)
        except Exception as e:
            pass

        finally:
            pass

    def getLogMessage(self, message):

        frame, filename, lineNo, functionName, code, unknowField = inspect.stack(
        )[3]
        return "%s - line:%s - function:%s %s" % (filename, lineNo,
                                                  functionName, message)

    def Output_terminal(self, message, levelname):
        print("{asctime} - {name} - {levelname} - {message}".format(asctime=time.strftime(
            "%H:%M:%S", time.localtime()), name=self.logger_name, levelname=levelname, message=message))

    def Output_file(self, message, levelname):
        try:
            with open(self.log_data_dir + "/" + self.logger_name + ".log",
                      "a",
                      encoding="utf8") as fp:
                fp.write("{asctime} - {levelname} - {message}".format(asctime=time.strftime(
                    "%H:%M:%S", time.localtime()), levelname=levelname, message=message + "\n"))
                fp.flush()
                fp.close()
        except Exception as e:
            pass
        finally:
            self.Create_logger()

    def debug(self, *args, **kwargs):
        args = [str(i) for i in args]
        self.Output_terminal(message="".join(args), levelname=logging.debug)
        self.Output_file(message="".join(args), levelname=logging.debug)

    def info(self, *args, **kwarg):
        args = [str(i) for i in args]
        # self.Output_terminal(message="".join(args), levelname=logging.debug)
        self.Output_file(message="".join(args), levelname=logging.info)

    def warning(self, *args, **kwarg):
        args = [str(i) for i in args]
        self.Output_file(message="".join(args), levelname=logging.warning)

    def error(self, *args, **kwarg):
        args = [str(i) for i in args]
        self.Output_file(message="".join(args), levelname=logging.error)

    def critical(self, *args, **kwarg):
        args = [str(i) for i in args]
        self.Output_file(message="".join(args), levelname=logging.critical)

    def __del__(self):
        self.stop = True

    def run(self):
        while True:
            if self.stop:
                break
            time.sleep(_while_wait_time)
            loctime = time.strftime("%H:%M", time.localtime(time.time()))
            if loctime == _log_rewriting_time:
                self.Create_logger()
                self.remove_old_log()
                time.sleep(29)


if __name__ == "__main__":
    logger = getLogger("test")
    while True:
        logger.debug("123")
        logger.info("456")
        time.sleep(3)
